package com.sgcc.nfc.lock.core.nfc

import android.nfc.Tag
import android.nfc.tech.NfcA
import android.util.Log

/**
 * NFC诊断工具类，用于帮助调试NFC开关锁问题
 */
object NfcDiagnostics {
    
    private const val TAG = "NfcDiagnostics"
    
    /**
     * 诊断NFC标签的基本信息
     */
    fun diagnoseTag(tag: Tag): TagDiagnosticInfo {
        val tagId = tag.id?.joinToString(separator = "") { "%02X".format(it) } ?: "UNKNOWN"
        val techList = tag.techList?.toList() ?: emptyList()
        val isNfcASupported = techList.contains("android.nfc.tech.NfcA")
        
        Log.d(TAG, "Tag ID: $tagId")
        Log.d(TAG, "Supported technologies: ${techList.joinToString()}")
        Log.d(TAG, "NFC-A supported: $isNfcASupported")
        
        return TagDiagnosticInfo(
            tagId = tagId,
            supportedTechnologies = techList,
            isNfcASupported = isNfcASupported
        )
    }
    
    /**
     * 诊断NFC-A连接状态
     */
    suspend fun diagnoseNfcAConnection(tag: Tag): ConnectionDiagnosticInfo {
        val nfcA = NfcA.get(tag)
        if (nfcA == null) {
            Log.e(TAG, "NFC-A not available for this tag")
            return ConnectionDiagnosticInfo(
                isNfcAAvailable = false,
                canConnect = false,
                maxTransceiveLength = 0,
                timeout = 0,
                errorMessage = "NFC-A not available"
            )
        }
        
        return try {
            nfcA.connect()
            val maxLength = nfcA.maxTransceiveLength
            val timeout = nfcA.timeout
            
            Log.d(TAG, "NFC-A connection successful")
            Log.d(TAG, "Max transceive length: $maxLength")
            Log.d(TAG, "Timeout: $timeout ms")
            
            nfcA.close()
            
            ConnectionDiagnosticInfo(
                isNfcAAvailable = true,
                canConnect = true,
                maxTransceiveLength = maxLength,
                timeout = timeout,
                errorMessage = null
            )
        } catch (e: Exception) {
            Log.e(TAG, "NFC-A connection failed", e)
            ConnectionDiagnosticInfo(
                isNfcAAvailable = true,
                canConnect = false,
                maxTransceiveLength = 0,
                timeout = 0,
                errorMessage = e.message ?: "Unknown connection error"
            )
        }
    }
    
    /**
     * 测试基本的NFC通信
     */
    suspend fun testBasicCommunication(tag: Tag): CommunicationDiagnosticInfo {
        val nfcA = NfcA.get(tag) ?: return CommunicationDiagnosticInfo(
            canCommunicate = false,
            startCommandSuccess = false,
            errorMessage = "NFC-A not available"
        )
        
        return try {
            nfcA.connect()
            
            // 测试start命令
            val startSuccess = NfcRawHelper.start(nfcA)
            Log.d(TAG, "Start command result: $startSuccess")
            
            nfcA.close()
            
            CommunicationDiagnosticInfo(
                canCommunicate = true,
                startCommandSuccess = startSuccess,
                errorMessage = if (!startSuccess) "Start command failed" else null
            )
        } catch (e: Exception) {
            Log.e(TAG, "Communication test failed", e)
            CommunicationDiagnosticInfo(
                canCommunicate = false,
                startCommandSuccess = false,
                errorMessage = e.message ?: "Communication test failed"
            )
        }
    }
    
    /**
     * 生成完整的诊断报告
     */
    suspend fun generateDiagnosticReport(tag: Tag): DiagnosticReport {
        Log.d(TAG, "Generating diagnostic report...")
        
        val tagInfo = diagnoseTag(tag)
        val connectionInfo = diagnoseNfcAConnection(tag)
        val communicationInfo = testBasicCommunication(tag)
        
        val overallStatus = when {
            !tagInfo.isNfcASupported -> DiagnosticStatus.NFC_A_NOT_SUPPORTED
            !connectionInfo.canConnect -> DiagnosticStatus.CONNECTION_FAILED
            !communicationInfo.canCommunicate -> DiagnosticStatus.COMMUNICATION_FAILED
            !communicationInfo.startCommandSuccess -> DiagnosticStatus.START_COMMAND_FAILED
            else -> DiagnosticStatus.OK
        }
        
        return DiagnosticReport(
            status = overallStatus,
            tagInfo = tagInfo,
            connectionInfo = connectionInfo,
            communicationInfo = communicationInfo,
            recommendations = generateRecommendations(overallStatus)
        )
    }
    
    private fun generateRecommendations(status: DiagnosticStatus): List<String> {
        return when (status) {
            DiagnosticStatus.NFC_A_NOT_SUPPORTED -> listOf(
                "此标签不支持NFC-A协议",
                "请确认使用的是正确的NFC锁标签",
                "检查标签是否损坏"
            )
            DiagnosticStatus.CONNECTION_FAILED -> listOf(
                "无法连接到NFC标签",
                "请将手机更靠近标签",
                "确保标签在NFC感应区域内",
                "检查手机NFC功能是否正常开启"
            )
            DiagnosticStatus.COMMUNICATION_FAILED -> listOf(
                "NFC通信失败",
                "请重新尝试操作",
                "确保操作过程中手机与标签保持稳定接触",
                "检查是否有其他NFC设备干扰"
            )
            DiagnosticStatus.START_COMMAND_FAILED -> listOf(
                "NFC启动命令失败",
                "标签可能不是有效的锁具标签",
                "请确认标签类型是否正确",
                "联系管理员确认标签配置"
            )
            DiagnosticStatus.OK -> listOf(
                "NFC通信正常",
                "如果仍然无法开关锁，请检查密码配置",
                "确认用户权限是否正确"
            )
        }
    }
}

data class TagDiagnosticInfo(
    val tagId: String,
    val supportedTechnologies: List<String>,
    val isNfcASupported: Boolean
)

data class ConnectionDiagnosticInfo(
    val isNfcAAvailable: Boolean,
    val canConnect: Boolean,
    val maxTransceiveLength: Int,
    val timeout: Int,
    val errorMessage: String?
)

data class CommunicationDiagnosticInfo(
    val canCommunicate: Boolean,
    val startCommandSuccess: Boolean,
    val errorMessage: String?
)

data class DiagnosticReport(
    val status: DiagnosticStatus,
    val tagInfo: TagDiagnosticInfo,
    val connectionInfo: ConnectionDiagnosticInfo,
    val communicationInfo: CommunicationDiagnosticInfo,
    val recommendations: List<String>
)

enum class DiagnosticStatus {
    OK,
    NFC_A_NOT_SUPPORTED,
    CONNECTION_FAILED,
    COMMUNICATION_FAILED,
    START_COMMAND_FAILED
}